﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
using DownLoad.Helpers;

namespace DownLoad.Common
{
    public class BusinessProcess
    {
        //static SqlHelper sqlHelper = new SqlHelper();
        /// <summary>
        /// 反序列XML文件
        /// </summary>
        /// <param name="path">the path of the xml file</param>
        /// <param name="object_type">the object type you want to deserialize</param>
        public static T DeserializeFromXml<T>(string path) where T : class
        {
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StreamReader reader = new StreamReader(path))
            {
                return serializer.Deserialize(reader) as T;
            }
        }
        /// <summary>
        /// 获取项目号的文件夹路径
        /// </summary>
        /// <returns></returns>
        public static string GetProjectNoDirectoryPath(string projectNo)
        {
            try
            {
                string[] arrayCustomers = Directory.GetDirectories(Global.AppConfigs.PathInfo.Server);
                foreach (var c in arrayCustomers)
                {
                    string[] arrayProjectNos = Directory.GetDirectories(c);
                    foreach (var p in arrayProjectNos)
                    {
                        if (p.Substring(p.LastIndexOf('\\')+1)==projectNo && !p.Contains("OQC"))
                        {
                            return p;
                        }
                    }
                }
            }
            catch
            {
                return "";
            }
            return "";
        }
        /// <summary>
        /// 把一个文件夹下面所有文件复制到另一个文件夹下
        /// </summary>
        /// <param name="srcPath">源路径</param>
        /// <param name="destPath"></param>
        public static void CopyDirectory(string srcPath, string destPath, List<string> lstexeFiles)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //获取目录下（不包含子目录）的文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)     //判断是否文件夹
                    {
                        if (!Directory.Exists(destPath + "\\" + i.Name))
                        {
                            Directory.CreateDirectory(destPath + "\\" + i.Name);   //目标目录下不存在此文件夹即创建子文件夹
                        }
                        CopyDirectory(i.FullName, destPath + "\\" + i.Name, lstexeFiles);    //递归调用复制子文件夹
                    }
                    else
                    {
                        //收集EXE文件
                        if (i.Extension==".exe" && !i.Name.Contains(".vshost.exe"))
                            lstexeFiles.Add(Path.Combine(destPath,i.Name));
                        if (!File.Exists(Path.Combine(destPath, i.Name)))
                        {
                            File.Create(Path.Combine(destPath, i.Name)).Close();
                            //加异常捕获是原因超长路径会报未找到路径的一部分错误，当报错的时候使用CMD命令拷贝
                            try
                            {
                                File.Copy(i.FullName, Path.Combine(destPath, i.Name), true);
                            }
                            catch (Exception ex)
                            {
                                if (ex.Message.Contains("未能找到路径"))
                                {
                                    string output = string.Empty;
                                    CmdHelper.CopyFilesFromShareToLocal(i.FullName, Path.Combine(destPath, i.Name), out output);
                                }
                            }
                            
                        }
                        else 
                        {
                            FileInfo fileInfo = new FileInfo(Path.Combine(destPath, i.Name));
                            string destFileLastWriteTime= fileInfo.LastWriteTime.ToString();//获取本地文件最后一次写入的时间
                            //比较本地和服务器文件的修改时间，如果一样就跳过，不一样就拷贝。这样可以节省时间。
                            if (i.LastWriteTime.ToString() != destFileLastWriteTime)
                            {
                                //加异常捕获是原因超长路径会报未找到路径的一部分错误，当报错的时候使用CMD命令拷贝
                                try
                                {
                                    File.Copy(i.FullName, Path.Combine(destPath, i.Name), true);
                                }
                                catch (Exception ex)
                                {
                                    if (ex.Message.Contains("未能找到路径"))
                                    {
                                        string output = string.Empty;
                                        CmdHelper.CopyFilesFromShareToLocal(i.FullName, Path.Combine(destPath, i.Name), out output);
                                    }
                                }
                            }
                            
                        }
                       
                    }
                }
            }
            catch (Exception e)
            {
               //Console.WriteLine(e.Message);
               throw new Exception(e.Message);
            }
        }
        /// <summary>
        /// 直接删除指定目录下的所有文件及文件夹(保留目录)
        /// </summary>
        /// <param name="strPath">文件夹路径</param>
        /// <returns>执行结果</returns>
        public static bool DeleteDir(string strPath)
        {
            try
            {
                // 清除空格
                strPath = @strPath.Trim().ToString();
                // 判断文件夹是否存在
                if (System.IO.Directory.Exists(strPath))
                {
                    // 获得文件夹数组
                    string[] strDirs = System.IO.Directory.GetDirectories(strPath);
                    // 获得文件数组
                    string[] strFiles = System.IO.Directory.GetFiles(strPath);
                    // 遍历所有子文件夹
                    foreach (string strFile in strFiles)
                    {
                        // 删除文件夹
                        System.IO.File.Delete(strFile);
                    }
                    // 遍历所有文件
                    foreach (string strdir in strDirs)
                    {
                        // 删除文件
                        System.IO.Directory.Delete(strdir, true);
                    }
                }
                // 成功
                return true;
            }
            catch (Exception Exp) // 异常处理
            {
                // 异常信息
                System.Diagnostics.Debug.Write(Exp.Message.ToString());
                // 失败
                return false;
            }
        }
        /// <summary>
        /// 关闭相关进程
        /// </summary>
        /// <param name="processName"></param>
        public static void CloseProcess(string processName)
        {
            try
            {
                processName = processName.Replace(".exe", ""); //去掉.exe后缀因为p.ProcessName获取的名称是不带后缀的
                Process[] processArray = Process.GetProcesses();
                foreach (var p in processArray)
                {
                    if (p.ProcessName == processName)
                    {
                        p.Kill();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
        /// <summary>
        /// 启动进程
        /// </summary>
        /// <param name="fileName"></param>
        public static void StartProcess(string fileName)
        {
            try
            {
                ProcessStartInfo info = new ProcessStartInfo();
                info.FileName = fileName;
                info.Arguments = "";
                info.UseShellExecute = false;
                info.WorkingDirectory = fileName.Substring(0, fileName.LastIndexOf('\\'));
                Process pro = Process.Start(info);
                //Process.Start(fileName);
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("请求的操作需要提升"))
                {
                    MessageBoxHelper.ShowWarning("正在打开的测试软件需要管理员权限\r\n请关闭下载软件然后以管理员身份运行");
                }
                else
                {
                    throw new Exception(ex.Message);
                }
                
            }
        }
        /// <summary>
        /// 通过工单号获取成品料号
        /// </summary>
        /// <param name="so">工单号</param>
        public static string GetPartNumberBySo(string so)
        {
            string projectNo = string.Empty;
            StringBuilder sql = new StringBuilder();
            try
            {
                sql.Append("select Item from view_work_inf where WorkNo='"+so+"'");
                projectNo=SqlHelper.GetInstance().ExecuteScalar<string>(sql.ToString());
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return projectNo;
        }
    }
}
